<template>
  <div class="login-user">
    <el-form :model="account" label-width="90px" :rules="accountRules" ref="ruleFormRef" status-icon>
      <el-form-item label="用户账号:" prop="name">
        <el-input v-model="account.name" />
      </el-form-item>
      <el-form-item label="用户密码:" prop="password">
        <el-input v-model="account.password" />
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormInstance, FormRules } from 'element-plus';
import useStore from '@/store/modules/user';
import { useRouter, useRoute } from 'vue-router';
import { ElNotification } from 'element-plus';
import { getTime } from '@/utils/tims';

//获取路由器
let $router = useRouter();
//路由对象
let $route = useRoute();

const loginStore = useStore();

interface RuleForm {
  name: string;
  password: string;
}

const emitLoading = defineEmits(['changeValue']);

// 定义表单内部数据
const account = reactive<RuleForm>({
  name: 'admin',
  password: 'atguigu123',
});

// 自定义验证规则
const validatePass = (rule: any, value: any, callback: any) => {
  if (/^[a-z0-9]{6,}$/.test(value)) {
    callback();
  } else {
    callback(new Error('请输入密码~'));
  }
};

// 定义验证规则
const ruleFormRef = ref<FormInstance>();
const accountRules = reactive<FormRules<RuleForm>>({
  name: [
    { required: true, message: '请输入账号~', trigger: 'blur' },
    { pattern: /^[a-z0-9]{3,20}$/, message: '必须是3~20个字母或数字', trigger: 'blur' },
  ],
  // password: [
  //   { required: true, message: '必须输入密码~', trigger: 'blur' },
  //   { pattern: /^[a-z0-9]{6,}$/, message: '密码必须在6位以上的数字或者字母', trigger: 'blur' },
  // ],
  password: [{ required: true, validator: validatePass, trigger: 'blur' }],
});

const loginAction = async () => {
  await ruleFormRef.value?.validate(async (isValid) => {
    if (!isValid) return ElMessage.warning({ message: '账号或者密码错误' });
    const username = account.name;
    const password = account.password;
    try {
      emitLoading('changeValue', true);
      // 保证登录成功
      await loginStore.userLoginAction({ username, password });
      ElNotification({
        type: 'success',
        message: '登录成功',
        title: `Hi, ${getTime()}`,
        duration: 1000,
      });
      setTimeout(() => {
        //编程式导航跳转到展示数据首页
        //判断登录的时候,路由路径当中是否有query参数，如果有就往query参数挑战，没有跳转到首页
        let redirect: any = $route.query.redirect;
        $router.push({ path: redirect || '/' });
        emitLoading('changeValue', false);
      }, 100);
    } catch (error) {
      emitLoading('changeValue', false);
      ElNotification({
        type: 'error',
        message: (error as Error).message,
        duration: 1000,
      });
    }
  });
};

// 定义暴露的属性和方法
defineExpose({
  loginAction,
});
</script>

<style lang="scss" scoped></style>
